package com.base.cn.platform.os.common.filter;

import com.base.cn.platform.os.common.constants.CommonConstants;
import com.base.cn.platform.os.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * 租户数据过滤器
 *
 * @author s.li
 * @create 2018-04-16-19:59
 */
//@WebFilter(filterName = "tenantDataFilter",urlPatterns = "/*")
//@Component
public class TenantDataFilter implements Filter {
    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(".js",".css",".png",".jpg")));
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");
        boolean allowedPath = ALLOWED_PATHS.contains(path);
        if(allowedPath){//不需要处理
            logger.debug("不处理的的url:"+path);
        }else{//需要处理的
            //通过头信息获取租户ID
            String tenantId = request.getHeader(CommonConstants.TENANT_ID_NAME);
            if(StringUtils.isEmpty(tenantId)){//如果通过头获取不到租户ID，则通过域名去获取
                tenantId = "0";
            }
            CommonConstants.threadLocal.set(tenantId);
        }
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
